<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api'
import { Message } from '@arco-design/web-vue'

const $route = useRoute()
const $router = useRouter()

const keyword = ref('')
const productList = ref([])
const listData = ref() // 部门列表
const page = ref(1)
const pageSize = ref(10)
const listTotal = ref(0)
const listLoading = ref(false)
const formData = ref({
  id: null,
  name: '',
  permission_id: [],
  data_divide: [],
}) // 部门表单
const formVisible1 = ref(false) // 部门列表弹窗
const formVisible = ref(false) // 部门管理弹窗

const getListData = async (page) => {
  listLoading.value = true
  try {
    const res = await api.get('system/departmentList', {
      params: {
        keyword: keyword.value,
        page,
        pageSize: pageSize.value,
      },
    })
    console.log('res', res)
    listData.value = res.data.items
    listTotal.value = res.data.pageInfo.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const getMenuAllList = async () => {
  try {
    const res = await api.get('system/menuList')
    console.log('res', res)
    productList.value = res.data
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const deleteItem = async (id) => {
  try {
    const res = await api.get('system/delDepartment/' + id)
    Message.success(res.message)
    getListData(1)
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const showFormData = async (record) => {
  if (record) {
    formData.value.id = record.id
    formData.value.name = record.name
    formData.value.permission_id = record.permission_id
      ? record.permission_id.split(',').map((e) => e * 1)
      : []
    formData.value.data_divide = record.data_divide
      ? record.data_divide.split(',').map((e) => e * 1)
      : []
  } else {
    resetFormData()
  }
  formVisible.value = true
} // 显示部门表单

const formSubmit = async () => {
  console.log('formData', formData.value)
  var obj = { ...formData.value }
  obj.permission_id = obj.permission_id.toString()
  obj.data_divide = obj.data_divide.toString()
  if (!obj.name) {
    Message.error('部门名称不可为空')
    return false
  }
  if (formData.value.id) {
    try {
      const res = await api.post('system/updateDepartment', obj)
      Message.success(res.message)
      getListData(1)
      resetFormData()
    } catch (error) {
      console.error('error', error)
      return false
    }
  } else {
    try {
      const res = await api.post('system/createDepartment', obj)
      Message.success(res.message)
      formVisible.value = false
      getListData(1)
      resetFormData()
    } catch (error) {
      console.error('error', error)
      return false
    }
  }
} // 提交部门表单

const resetFormData = async () => {
  formData.value = {
    id: null,
    name: '',
    permission_id: [],
    data_divide: [],
  }
}

const handleChangePermissionId = async (e) => {
  // 取交集
  formData.value.data_divide = formData.value.permission_id.filter((item) =>
    formData.value.data_divide.includes(item)
  )
}

const handleChangeDataDivide = async (e) => {
  // 取并集
  formData.value.permission_id = [
    ...new Set([...formData.value.permission_id, ...e]),
  ]
}

getListData(1)
getMenuAllList()
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>
        <a-input :style="{ width: '240px' }"
                 v-model="keyword"
                 placeholder="按部门名称查询"
                 allow-clear />

        <a-button @click="getListData(1)"
                  type="primary">查询</a-button>
      </a-space>
      <a-button @click="showFormData()"
                type="primary">新增部门</a-button>
    </div>

    <a-table :data="listData">
      <template #columns>
        <a-table-column title="序号"
                        :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="部门名称"
                        data-index="name"></a-table-column>
        <a-table-column title="创建时间"
                        data-index="created_at"></a-table-column>
        <!-- <a-table-column title="修改时间"
                        data-index="updated_at"></a-table-column> -->
        <a-table-column title="操作"
                        align="center"
                        :width="300">
          <template #cell="{ record }">
            <a-space>
              <a-popconfirm @ok="deleteItem(record.id)"
                            content="确认删除该数据吗?"
                            type="warning">
                <a-button type="primary"
                          status="danger"
                          size="mini">删除</a-button>
              </a-popconfirm>
              <a-button @click="showFormData(record)"
                        type="primary"
                        size="mini">编辑</a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal :title="formData.id ? '编辑部门':'添加部门'"
             width="600px"
             :on-before-ok="formSubmit"
             v-model:visible="formVisible">
      <a-form>
        <a-form-item label="部门名称">
          <a-input :style="{width:'400px'}"
                   v-model="formData.name"
                   placeholder="请输入部门名称"
                   allow-clear></a-input>
        </a-form-item>
        <a-form-item label="权限">
          <a-checkbox-group v-model="formData.permission_id"
                            @change="handleChangePermissionId">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="数据隔离">
          <a-checkbox-group v-model="formData.data_divide"
                            @change="handleChangeDataDivide">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{ item.title }}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>